import api from '@/api/app.js'

export default function usePay() {

    const orderNumber = ref('')

    function createWxPreOrder(order_number = '') {
        return new Promise((resolve, reject) => {
            orderNumber.value = order_number
            api.wxPayOrder({
                order_number
            }).then(res => {
                const data = JSON.parse(res.data.data)
                const {
                    timeStamp,
                    nonceStr,
                    paySign
                } = data;

                const payParams = {
                    provider: 'wxpay',
                    orderInfo: data,
                    timeStamp,
                    nonceStr,
                    package: data.package,
                    signType: 'MD5',
                    paySign,
                    success: e => {
                        console.log('支付成功')
                        resolve()
                    },
                    fail: err => {
                        if (err.errMsg.indexOf('取消') > -1 || err.errMsg.indexOf('cancel') > 1 || err
                            .errMsg.indexOf('-2') > -1) {
                            uni.showToast({
                                icon: 'none',
                                title: '取消支付'
                            })
                        } else {
                            uni.showToast({
                                icon: 'none',
                                title: '支付遇到错误，请稍候重试'
                            })
                            console.log(err);
                        }
                        reject()
                    },
                    complete: () => {
                    }
                };
                console.log(payParams);
                uni.requestPayment(payParams);
            })
        })
    }

    async function checkOrder(order_number) {
        return new Promise((resolve, reject) => {
            let orderCheckTime = 10
            const orderCheckTimer = setInterval(async () => {
                const res = await orderDetail(order_number)
                console.log('res', res)
                --orderCheckTime
                if (res.data.data.pay_status === "1") {
                    clearInterval(orderCheckTimer)
                    resolve(res.data.data)
                } else if (res.data.data.pay_status === "-1") {
                    clearInterval(orderCheckTimer)
                    reject('支付已取消')
                } else {
                    if (orderCheckTime <= 0) {
                        clearInterval(orderCheckTimer)
                        reject('支付结果查询失败')
                    }
                }
            }, 1000)
        })
    }

    function orderDetail(order_number) {
        return api.orderDetail({
            order_number
        })
    }

    return {
        createWxPreOrder,
        checkOrder,
    }
}